package cn.ecnu.note.service.impl;

import cn.ecnu.common.Constant;
import cn.ecnu.common.Permission;
import cn.ecnu.exception.RRXException;
import cn.ecnu.note.mapper.ReplyMapper;
import cn.ecnu.note.pojo.Note;
import cn.ecnu.note.pojo.Reply;
import cn.ecnu.note.service.ReplyService;
import cn.ecnu.note.vo.ReplyFrontVo;
import cn.ecnu.note.vo.ReplyVo;
import cn.ecnu.note.vo.ViewReplyVo;
import cn.ecnu.utils.PaginationUtil;
import cn.ecnu.vo.common.Pagination;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class ReplyServiceImpl implements ReplyService {

    @Resource
    private ReplyMapper replyMapper;

    @Override
    public ReplyVo addReply(ReplyFrontVo vo) {
        Reply reply = new Reply();
        BeanUtils.copyProperties(vo, reply);
        reply.setFlag(1); // 设置为可见
        replyMapper.insertReply(reply);
        return replyMapper.getReplyVoById(reply.getReplyId());
    }

    @Override
    public int deleteReply(Integer replyId, Integer userId, Integer permission) {
        Reply reply = replyMapper.getReplyById(replyId);
        if (reply == null) throw new RRXException(Constant.NO_RESOURCE.getMsg(), Constant.NO_RESOURCE.getCode());
        if (NumberUtils.compare(userId, reply.getFromId()) != 0 && !Permission.isAdmin(permission))
            throw new RRXException(Constant.NO_PERMISSION.getMsg(), Constant.NO_PERMISSION.getCode());
        // 最终删除
        return replyMapper.deleteReplyById(replyId);
    }

    @Override
    public ViewReplyVo getReplyByCommentId(Integer commentId, Integer pageNum) {
        int pageSize = 2;
        int totalSize = replyMapper.getReplyCountByCommentId(commentId);

        Pagination pagination = PaginationUtil.paging(pageNum, totalSize, pageSize, "/reply/getReplyByCommentId/" + commentId);
        pageNum = pagination.getCurrentPage();

        List<ReplyVo> vo = replyMapper.getReplyVoByCommentId(commentId, (pageNum - 1) * pageSize, pageSize);
        ViewReplyVo res = new ViewReplyVo();

        res.setRepliesInfo(vo);
        res.setPagination(pagination);
        return res;
    }
}
